package net.yla.smartbus.module.controller.web.ba.file;

import net.yla.smartbus.core.api.ApiResult;
import net.yla.smartbus.core.base.BaseController;
import net.yla.smartbus.core.exception.AppException;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author : yang lei
 * @version : 1.0
 * @date : Created in 15:59 2020/9/11
 * @description : 文件上传
 */
@RestController
@RequestMapping("/api/web/file")
public class FileController extends BaseController {

    /**
     * 返回的是文件上传后的地址
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ApiResult fileLoad(MultipartFile file) {

        //创建文件夹
        String uri = "F://static//picture//";
        File fileDir = new File(uri);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        String imgUrl = null;
        UUID uuid = null;
        if (file != null && file.getSize() != 0) {
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            uuid = UUID.randomUUID();
            String fileName = uuid + suffix;
            String serverUri = uri + fileName;
            //创建文件
            File serverFile = new File(serverUri);
            imgUrl = "/static/picture/" + fileName;
            try {
                file.transferTo(serverFile);
            } catch (IOException e) {
                throw new AppException("文件上传失败", 501);
            }
        }
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("url", imgUrl);
//        jsonObject.put("uid", uuid);
        return success(imgUrl);
    }

}
